﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Reflection;

namespace RIFT.Unpacker
{
    using RIFT.Assets;

    class Program
    {
        static void Main(string[] args)
        {
            if (args.Length == 0) 
            {
                Console.WriteLine("No filename specified. First argument should be the full path to a .pak file");
                Console.Read();
                return;
            }
            
            if (File.Exists(args[0]))
            {
                string filename = args[0];
                
                string appPath = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);

                var builder = new StringBuilder();

                Console.WriteLine("Reading Headers...");
                var files = RiftPackage.GetFiles(filename);
                
                double count = (double)files.Count();
                int i = 0;

                byte[] ddsFourCC = new byte[4] { 0x44, 0x44, 0x53, 0x20 };

                foreach (var file in files)
                {
                    var directory = Path.Combine(appPath, Path.GetFileNameWithoutExtension(filename));

                    if (!Directory.Exists(directory))
                    {
                        Directory.CreateDirectory(directory);
                    }

                    string ext = "dat";
                    if (ddsFourCC.SequenceEqual(file.FourCC))
                    {
                        ext = "dds";
                    }

                    string path = string.Format("{0}/{1:0000}.{2}", directory, ++i, ext);
                    
                    double percentage = (100 / count) * i;

                    Console.Clear();
                    Console.WriteLine("Unpacking {0}: {1}/{2} ({3}%)",
                        Path.GetFileName(path), i, count, (int)percentage);
                    
                    File.WriteAllBytes(path, file.Data);
                }

                Console.WriteLine("Finished unpacking {0}", Path.GetFileName(args[0]));
                Console.WriteLine("Press any key to close.");
                Console.Read();
            }
            else
            {
                Console.WriteLine("{0} could not be found", args[0]);
                Console.Read();
            }
        }
    }
}
